<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="trainCode">
        <el-input
          v-model="queryParams.trainCode"
          placeholder="请输入车次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="date">
        <el-date-picker clearable
          v-model="queryParams.date"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入站名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['business:daily-train-station:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['business:daily-train-station:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['business:daily-train-station:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['business:daily-train-station:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 使用折叠面板展示分组数据 -->
    <el-collapse v-loading="loading">
      <el-collapse-item v-for="(group, index) in groupedStations" :key="index" :name="index">
        <template slot="title">
          <div class="train-group-title">
            <span class="train-code">车次: {{ group.trainCode }}</span>
            <span class="train-route">
              {{ getStationName(group.stations, 'first') }} → {{ getStationName(group.stations, 'last') }}
              <span class="station-count">(共{{ group.stations.length }}站)</span>
            </span>
          </div>
        </template>

        <!-- 嵌套表格显示该车次的所有站点 -->
        <el-table
          :data="group.stations"
          :row-style="{ height: '60px' }"
          @selection-change="handleSelectionChange"
          :default-sort="{prop: 'index', order: 'ascending'}"
        >
<!--          <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />-->
          <el-table-column show-overflow-tooltip label="站序" align="center" prop="index" sortable />
          <el-table-column show-overflow-tooltip label="ID" align="center" prop="id"  />
          <el-table-column show-overflow-tooltip label="日期" align="center" prop="date" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="车次编号" align="center" prop="trainCode" />
          <el-table-column show-overflow-tooltip label="站名" align="center" >
            <template slot-scope="scope">
              <span>
                {{ scope.row.name }}
                <span class="station-tag">({{ getStationType(group.trainType) }})</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="进站时间" align="center" prop="inTime"/>
          <el-table-column show-overflow-tooltip label="出站时间" align="center" prop="outTime"/>
          <el-table-column show-overflow-tooltip label="停站时长" align="center" prop="stopTime"/>
          <el-table-column show-overflow-tooltip label="里程(km)" align="center" prop="km"/>
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-edit"-->
<!--                @click="handleUpdate(scope.row)"-->
<!--                v-hasPermi="['business:daily-train-station:edit']"-->
<!--              >修改</el-button>-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-delete"-->
<!--                @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['business:daily-train-station:remove']"-->
<!--              >删除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination
      v-show="trainTotal>0"
      :total="trainTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每日车站对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车次编号" prop="trainCode">
          <el-input v-model="form.trainCode" placeholder="请输入车次编号" />
        </el-form-item>
        <el-form-item label="站序" prop="index">
          <el-input-number v-model="form.index" placeholder="请输入站序" />
        </el-form-item>
        <el-form-item label="站名" prop="name">
          <el-input v-model="form.name" placeholder="请输入站名" />
        </el-form-item>
        <el-form-item label="站名拼音" prop="namePinyin">
          <el-input v-model="form.namePinyin" placeholder="请输入站名拼音" />
        </el-form-item>
        <el-form-item label="进站时间" prop="inTime">
          <el-time-picker
            v-model="form.inTime"
            placeholder="请选择进站时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="出站时间" prop="outTime">
          <el-time-picker
            v-model="form.outTime"
            placeholder="请选择出站时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="停站时长" prop="stopTime">
          <el-time-picker
            v-model="form.stopTime"
            placeholder="请选择停站时长"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="里程(km)" prop="km">
          <el-input-number v-model="form.km" placeholder="请输入里程" :precision="2" :step="0.1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDailyTrainStationByGroup, getDailyTrainStation, delDailyTrainStation, addDailyTrainStation, updateDailyTrainStation } from "@/api/business/daily-train-station";

export default {
  name: "DailyTrainStation",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数(站点总数) - 保留但不用于分页
      total: 0,
      // 车次总数 - 用于分页显示
      trainTotal: 0,
      // 每日车站表格数据
      groupedStations: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        trainCode: null,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        trainCode: [
          { required: true, message: "车次编号不能为空", trigger: "blur" }
        ],
        index: [
          { required: true, message: "站序不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "站名不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询每日车站列表 */
    getList() {
      this.loading = true;
      listDailyTrainStationByGroup(this.queryParams).then(response => {
        this.groupedStations = response.rows;
        this.trainTotal = response.total; // 车次总数
        this.total = this.calculateTotalStations(); // 计算站点总数，仅用于其他功能
        this.loading = false;
      });
    },

    // 计算所有站点总数（非分页用）
    calculateTotalStations() {
      let totalStations = 0;
      if (this.groupedStations && this.groupedStations.length > 0) {
        this.groupedStations.forEach(group => {
          totalStations += group.stations ? group.stations.length : 0;
        });
      }
      return totalStations;
    },

    // 获取站点名称 (不使用sort方法，避免修改原数组)
    getStationName(stations, position) {
      if (!stations || stations.length === 0) {
        return '未知';
      }

      let result = '未知';
      let targetIndex = position === 'first' ? Number.MAX_VALUE : -1;

      for (const station of stations) {
        if (position === 'first' && station.index < targetIndex) {
          targetIndex = station.index;
          result = station.name;
        } else if (position === 'last' && station.index > targetIndex) {
          targetIndex = station.index;
          result = station.name;
        }
      }

      return result;
    },

    // 获取站点类型
    getStationType(type) {
      if (type === 'G') {
        return '高铁站';
      } else if (type === 'D') {
        return '火车站';
      } else {
        return '综合站';
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        trainCode: null,
        index: null,
        name: null,
        namePinyin: null,
        inTime: null,
        outTime: null,
        stopTime: null,
        km: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        date: null,
        trainCode: null,
        name: null
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每日车站";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailyTrainStation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每日车站";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDailyTrainStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDailyTrainStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每日车站编号为"' + ids + '"的数据项？').then(function() {
        return delDailyTrainStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/daily-train-station/export', {
        ...this.queryParams
      }, `daily-train-station_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
/* 折叠面板相关样式 */
.train-group-title {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.train-code {
  font-weight: bold;
  margin-right: 20px;
  min-width: 80px;
}

.train-route {
  min-width: 200px;
  color: #606266;
}

.station-count {
  font-size: 12px;
  color: #909399;
  margin-left: 5px;
}

.station-tag {
  font-size: 12px;
  color: #909399;
  margin: 0 2px;
}

.el-collapse-item__header {
  height: 60px;
  line-height: 60px;
  background-color: #f5f7fa;
  padding-left: 15px;
}

.el-collapse-item__content {
  padding: 10px;
}
</style>
